package chap09;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;

public class Socket_demo {
    public static void main(String args[]) {
//    IP_Address();
//        Get_ip_api();
        socket();
    }


    public static void IP_Address() {
        String ip;
        for (int i = 1; i <= 200; i++) {
            InetAddress host;
            ip = "192.168.1." + i;
            try {
                host = InetAddress.getByName(ip);
                if (host.isReachable(2000)) {//用1秒时间测试ip是否可达 2000=1s?      如果我用1秒呢？
                    String hostName = host.getHostName();//抓起用户名
                    System.out.println("IP地址" + ip + "主机名字是" + hostName);
                }
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("搜索完毕");
    }

    public static void Get_ip_api() {
        InetAddress ip;
        try {
            ip = InetAddress.getLocalHost();
            String localname = ip.getHostName();
            String localip = ip.getHostAddress();
            System.out.println("本机名:" + localname);//输出本机名
            System.out.println("本机ip地址" + localip);//把本机名输出
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public static void socket() {
        ServerSocket serversocket = null;
        PrintWriter out = null;
        try {
            serversocket = new ServerSocket(9999);//服务器

        } catch (Exception e) {
            System.out.println("尝试在9999端口创建");
            System.exit(1);
        }
        Socket clientsocket = null;//socket  用于两个链接的句柄
        try {
            clientsocket = serversocket.accept();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            out = new PrintWriter(clientsocket.getOutputStream(), true);
            out.println("hello wrold 这里是服务端");
            clientsocket.close();
            serversocket.close();
        } catch (IOException e) {
            System.out.println("PrintWriter failed");
        }


    }
}
